<template>
    <div class="container">
        <div class="header">
            <div style="width: 80%">
                <el-input clearable v-model="formData.name" type="textarea" placeholder="粘入智能识别"></el-input>
            </div>
            <el-button class="btn" :disabled="formLoading" type="primary" @click="blurChange">读取数据</el-button>
        </div>
        <div v-for="(form, index) in forms" :key="index">
            <el-form
                :model="form"
                :rules="formRules"
                label-width="130px"
                :ref="`form-${index}`"
            >
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item :label="`数据（${form.num}）`" prop="count">
                            <el-input clearable v-model="form.count" disabled placeholder="请输入名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="翻译数据" prop="name">
                            <el-input clearable v-model="form.name" placeholder="请输入名称"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <div v-if="!props.mode">
            <el-button :disabled="formLoading" type="primary" @click="handle">翻译</el-button>
            <el-button @click="exportToExcel">导出为 Excel</el-button>
        </div>
        <div v-if="!props.mode">
            <el-table :data="state.tableData" height="80vh">
                <!-- 添加序号列 -->
                <el-table-column type="index" label="序号" width="200"></el-table-column>
                <el-table-column v-for="item in columnData" :key="item.prop" :label="item.label" :prop="item.prop"/>
            </el-table>
        </div>
    </div>
</template>


<script setup lang="ts">
import {ref, reactive, getCurrentInstance, onUnmounted, onMounted, watch} from "vue";
import XEUtils from "xe-utils";
import * as XLSX from "xlsx";
import {copyValue, generateRandomCancerTypes} from "@/views/Home/index";
import {saveAs} from 'file-saver';
import {ElMessage} from "element-plus";

const { proxy } = getCurrentInstance()
const formData = ref({
    name: '',
})
const props = defineProps({
    modelValue: {
        type: Object,
        default: {}
    },
    tableData: {
        type: Array,
        default: []
    },
    // 组件模式
    mode: {
        type: Boolean,
        default: false
    }
})
onMounted(() => {
    if (!props.mode) {
        document.addEventListener('keydown', function(event) {
            if (event.key === 'Enter' || event.keyCode === 13) {
                blurChange()
            }
        });
    }
})

onUnmounted(() => {
    window.removeEventListener('keypress', blurChange);
})

const state = reactive({
    tableData: [],
    csvValue: ''
})
const formRules = reactive({
    count: [{ required: true, message: "不能为空", trigger: "blur" }],
    name: [{ required: true, message: "不能为空", trigger: "blur" }],
});
const formRef = ref(); // 表单 Ref
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const blurChange = (val) => {
    forms.value = []
    const array = formData.value.name.split(/\r?\n/).filter(Boolean);
    let sumObj = XEUtils.countBy(array.map(j => {
        return {
            name: j,
        }
    }),'name')
    forms.value = Object.assign(forms.value, XEUtils.orderBy(XEUtils.uniq(array).map(j => {
        return {
            count: j,
            num: sumObj[j]
        }
    })))
    state.tableData = array.map(j => {
        return {
            count: j,
        }
    })
    console.log(state.tableData)
    console.log(forms.value)
    emit('update:tableData', state.tableData)
    '2\t2\n' +
    '4\t4\n' +
    '5\t5\n'

}

const forms = ref([]);
const columnData = ref([
    {prop: 'count', label: '值'},
    {prop: 'name', label: '翻译值'},
]);

watch(
    forms.value,
    (n, o) => {
        emit('update:modelValue', o)
    },
    { deep: true }
)
watch(
    state.tableData,
    (n, o) => {
        emit('update:tableData', o)
    },
    { deep: true }
)
const emit = defineEmits(['update:modelValue','update:tableData'])
const handle = async () => {
// 获取所有表单的引用
    // 如果所有表单都通过校验
    if (await validate()) {
        console.log(forms.value)
        state.tableData = state.tableData.map(j => {
            let find = forms.value.find(k => k.count == j.count)
            if (find) {
                return {
                    count: j.count,
                    name: find.name
                }
            }
        })
        state.csvValue = state.tableData.map(type => `${type.name}`).join("\n");
        copyValue(state.csvValue)
        // 可以在这里执行后续操作，例如提交数据到服务器
    } else {
        console.log('1\n' +
            '2\n' +
            '1\n' +
            '2\n' +
            '3\n' +
            '2\n')
        alert('提交失败，请检查所有表单的输入！');
    }
};
const validate = async () => {
    if (!formData.value.name) {
        ElMessage({
            message: `翻译识别参数为空`,
            duration: 2000,
            type: 'warning',
        })
        return false
    }
    const formRefs = proxy.$refs;
    let allValid = true; // 用于标记所有表单是否都通过校验

    // 遍历所有表单并校验
    for (const key in formRefs) {
        if (formRefs[key][0] && formRefs[key][0]?.validate) {
            const isValid = await formRefs[key][0].validate()
            if (!isValid) {
                allValid = false; // 如果任何一个表单未通过校验，将 allValid 设置为 false
            }
        }
    }
    return allValid
}
const exportToExcel = () => {
    const newTableData = resetTableData();
    const worksheet = XLSX.utils.json_to_sheet(newTableData);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
    const excelBuffer = XLSX.write(workbook, {
        bookType: 'xlsx',
        type: 'array',
    });
    const data = new Blob([excelBuffer], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
    });
    saveAs(data, 'tableData.xlsx');
};
const resetTableData = () => {
    const propToLabelMap = new Map(columnData.value.map(item => [item.prop, item.label]));
    const restructuredTableData = state.tableData.map(row => {
        const newRow = {};
        for (const prop in row) {
            if (row.hasOwnProperty(prop) && propToLabelMap.has(prop)) {
                newRow[propToLabelMap.get(prop)] = row[prop];
            }
        }
        return newRow;
    });
    return restructuredTableData;
};
defineExpose({ validate })
</script>

<style scoped lang="scss">
.container {
    height: 100%;
    overflow-y: auto;
    background: #f7f8fa;
    margin: 10px 0;
}
.header{
    display: flex;
}
.btn{
    margin-left: 20px;
}
</style>
